package com.vector.ding.web.service.baseinfo;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.ActionResult;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.Constant;
import com.vector.ding.commons.util.BeanUtil;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.commons.util.web.RequestUtil;
import com.vector.ding.dao.mybatis.mapper.RzdbgsBaseInfoMapper;
import com.vector.ding.dao.mybatis.mapper.RzdbgsBizInfo1Mapper;
import com.vector.ding.dao.mybatis.model.RzdbgsBaseInfo;
import com.vector.ding.dao.mybatis.model.RzdbgsBaseInfoExample;
import com.vector.ding.dao.mybatis.model.RzdbgsBizInfo1;
import com.vector.ding.dao.mybatis.model.RzdbgsBizInfo1Example;
import com.vector.ding.exception.BaseException;

@Service
public class RzdbgsBaseInfoMgrService {
	
	@Autowired
	private RzdbgsBaseInfoMapper baseMapper;
	@Autowired
	private RzdbgsBizInfo1Mapper biz1Mapper;
	
	private static Logger logger = LoggerFactory.getLogger(GqtzgsBaseInfoMgrService.class);

	public RzdbgsBaseInfo getBaseInfo(String number) {
		return baseMapper.selectByPrimaryKey(number);
	}
	
	public RzdbgsBaseInfo getBaseInfoByName(String companyName) {
		RzdbgsBaseInfoExample example = new RzdbgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		List<RzdbgsBaseInfo> list = baseMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}

	public List<RzdbgsBaseInfo> getBaseInfo(int pageIndex, int pageSize,
			HttpServletRequest request) {
		if (pageSize != Integer.MAX_VALUE)
			PageHelper.startPage(pageIndex, pageSize, true);
		RzdbgsBaseInfoExample example = getBaseInfoExample(request);
		return baseMapper.selectByExample(example);
	}

	private RzdbgsBaseInfoExample getBaseInfoExample(HttpServletRequest request) {
		RzdbgsBaseInfoExample example = new RzdbgsBaseInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name")).trim();
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}

	public RzdbgsBaseInfo getBaseInfoBean(HttpServletRequest request) {
		Map<String, Object> paramMap = RequestUtil.getParamMap(request);
		Set<String> excludeProSet = CollectionUtil.asSet("registerFund");
		RzdbgsBaseInfo baseInfo = new RzdbgsBaseInfo();
		BeanUtil.fillBeanProperty(paramMap, baseInfo, excludeProSet);
		baseInfo.setRegisterFund(ExcelUtil.getDecimalValue(
				StringUtil.getString(paramMap.get("registerFund"))));
		if (StringUtil.isEmpty(baseInfo.getNumber()))
			baseInfo.setNumber(StringUtil.getUuid());
		
		return baseInfo;
	}

	public JSONObject insertBaseInfo(RzdbgsBaseInfo baseInfo) {
		if (existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("新增失败：存在编号为[%s]的记录!", baseInfo.getNumber()));
		
		int cnt = 0;
		try {
			cnt = baseMapper.insertSelective(baseInfo);
		} catch (Exception e) {
			if (logger.isDebugEnabled())
				e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("插入小贷投资公司基本信息记录失败：number为{}...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("新增记录失败"));
	}
	
	public JSONObject updateBaseInfo(RzdbgsBaseInfo baseInfo) {
		if (!existRecord(baseInfo.getNumber()))
			return ActionResult.fail(String.format("更新失败：不存在编号为[%s]的记录!", baseInfo.getNumber()));
		int cnt = 0;
		try {
			cnt = baseMapper.updateByPrimaryKeySelective(baseInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("更新小贷投资公司基本信息记录失败：未找到number为{}的记录...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? ActionResult.success() : 
			ActionResult.fail(String.format("更新基本信息记录失败，编号为[%s]", baseInfo.getNumber()));
	}
	
	public boolean existRecord(String number) {
		RzdbgsBaseInfoExample example = new RzdbgsBaseInfoExample();
		example.or().andNumberEqualTo(number);
		return baseMapper.countByExample(example) != 0;
	}

	public JSONObject delete(String[] ids) {
		int count = Constant.DaoOperation.UPDATE_FAILURE ;
		if (ids == null || ids.length == 0)
			count = 0;
		
		try {
			for (String id: ids) {
				// 删除业务1表中同名公司的记录数据
				RzdbgsBaseInfo baseInfo = getBaseInfo(id);
				if (baseInfo == null)
					continue;
				String companyName = baseInfo.getCompanyName();
				biz1Mapper.deleteByPrimaryKey(companyName);
				
				count += baseMapper.deleteByPrimaryKey(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ActionResult.fail("删除失败！");
		}
		
		if (count == Constant.DaoOperation.UPDATE_FAILURE)
			return ActionResult.fail("删除失败！");
		return ActionResult.success();
	}

	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 0;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheet("基本情况表");
			
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = BizConstant.Rzdbgs.START_ROW_NUM; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				if (isEnd(row))
					break;

				String companyName = row.getCell(BizConstant.Rzdbgs.COMPANY_NAME_CELL).toString();
				if (StringUtil.isEmpty(companyName))
					continue;
				String orgSystem = row.getCell(BizConstant.Rzdbgs.Base.ORG_SYSTEM_CELL).toString();
				if (!existBaseRecord(companyName)) {
					insertBaseInfo(companyName, orgSystem);
				}
				
				RzdbgsBizInfo1 bean = getBaseInfoBean(row);
				if (!exiestBiz1Record(companyName)) {
					biz1Mapper.insertSelective(bean);
				} else {
					RzdbgsBizInfo1Example example = new RzdbgsBizInfo1Example();
					example.or().andNumberEqualTo(companyName);
					biz1Mapper.updateByExampleSelective(bean, example);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
//			throw new BaseException(e);
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}
	
	private void insertBaseInfo(String companyName, String orgSystem) {
		RzdbgsBaseInfo baseInfo = new RzdbgsBaseInfo();
		baseInfo.setCompanyName(companyName);
		baseInfo.setNumber(UUID.randomUUID().toString());
		baseInfo.setOrgSystem(orgSystem);
		baseMapper.insertSelective(baseInfo);
	}

	private RzdbgsBizInfo1 getBaseInfoBean(HSSFRow row) {
		RzdbgsBizInfo1 bean = new RzdbgsBizInfo1();
		
		bean.setNumber(StringUtil.getUuid());
		bean.setRealReceiveFund(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.REAL_RECEIVE_FUND_CELL)));
		bean.setNetAsset(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.NET_ASSET_CELL)));
		bean.setTotalAsset(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.TOTAL_ASSET_CELL)));
		bean.setTotalFinancingFund(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.TOTAL_FINANCING_FUND)));
		bean.setCurYearFinancingFund(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.CUR_YEAR_FINANCING_FUND_CELL)));
		bean.setCurMonthFinancingBalance(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.CUR_MONTH_FINANCING_BABLANCE_CELL)));
		bean.setFinancingAccountNum(ExcelUtil.getIntegerValue(row.getCell(BizConstant.Rzdbgs.Biz1.FINANCING_ACCOUNT_NUM_CELL)));
		bean.setBondFund(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.BOND_FUND_CELL)));
		bean.setBondAccountNum(ExcelUtil.getIntegerValue(row.getCell(BizConstant.Rzdbgs.Biz1.BOND_ACCOUNT_NUM_CELL)));
		bean.setFinancingMagnifyTimes(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.FINANACING_MAGNIFY_TIMES_CELL)));
		bean.setAgainAssureBalance(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.AGAIN_ASSURE_BALNACE_CELL)));
		bean.setFrzxdbBalance(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.FRZXDB_BALANCE_CELL)));
		bean.setCurYearTotalIncom(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.CUR_YEAR_TOTAL_INCOM_CELL)));
		bean.setCurYearTotalBizIncom(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.CUR_YEAR_TOTAL_BIZ_INCOM_CELL)));
		bean.setDbywsrzyysrPercent(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.DBYWSRZYYSR_PERCENT_CELL)));
		bean.setCurYearNetProfit(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.CUR_YEAR_NET_PROFIT_CELL)));
		bean.setExternalInvestBalance(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.EXTERNAL_INVEST_BANLANCE_CELL)));
		bean.setDwtzzjzcPercent(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.DWTZZJZC_PERCENT_CELL)));
		bean.setOtherAccountsDue(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.OTHER_ACCOUNTS_DUE_CELL)));
		bean.setOtherAccountPayable(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.OTHER_ACCOUNT_PAYABLE_CELL)));
		bean.setDepositCashImport(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.DEPOSIT_CASH_IMPORT_CELL)));
		bean.setDepositCashExport(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.DEPOSIT_CASH_EXPORT_CELL)));
		bean.setZmhbzjBalance(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.ZMHBZJ_BALANCE_CELL)));
		bean.setQtysjcqtzJzcPercent(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.QTYSJCQTZ_JZC_PERCENT_CELL)));
		bean.setZmysdck(ExcelUtil.getCellDecimalValue(row.getCell(BizConstant.Rzdbgs.Biz1.ZMYSDCK_CELL)));
		bean.setQtyezbcgjzc5ysdkm(row.getCell(BizConstant.Rzdbgs.Biz1.QTYEZBCGJZC5YSDKM_CELL).toString());
		
		return bean;
	}
	
	private boolean isEnd(HSSFRow row) {
		String stringValue = row.getCell(0).toString();
		if (StringUtil.isEmpty(stringValue))
			return true;
		
		return false;
	}
	
	private boolean exiestBiz1Record(String companyName) {
		RzdbgsBizInfo1Example example = new RzdbgsBizInfo1Example();
		example.or().andNumberEqualTo(companyName);
		return biz1Mapper.countByExample(example) != 0;
	}
	
	private boolean existBaseRecord(String companyName) {
		RzdbgsBaseInfoExample example = new RzdbgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		return baseMapper.countByExample(example) != 0;
	}
	
	public boolean exiestCompany(String companyName) {
		RzdbgsBaseInfoExample example = new RzdbgsBaseInfoExample();
		example.or().andNumberEqualTo(companyName);
		return baseMapper.countByExample(example) != 0;
	}

/*	private boolean checkRowData(HSSFRow row) {
		String number = StringUtil.getString((int)row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL).getNumericCellValue());
		if (StringUtil.isEmpty(number))
			return false;
		
		return !existRecord(number);
	}*/

}
